package com.liyuxiang.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyuxiang.yygh.common.exception.YyghException;
import com.liyuxiang.yygh.common.helper.JwtHelper;
import com.liyuxiang.yygh.common.result.ResultCodeEnum;
import com.liyuxiang.yygh.enums.AuthStatusEnum;
import com.liyuxiang.yygh.model.user.Patient;
import com.liyuxiang.yygh.model.user.UserInfo;
import com.liyuxiang.yygh.user.mapper.UserInfoMapper;
import com.liyuxiang.yygh.user.service.PatientService;
import com.liyuxiang.yygh.user.service.UserInfoService;
import com.liyuxiang.yygh.vo.user.LoginVo;
import com.liyuxiang.yygh.vo.user.UserAuthVo;
import com.liyuxiang.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        Map<String, Object> result = new HashMap<>();
        //loginVo获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        String redisCode = redisTemplate.opsForValue().get("sms-" + phone).replace("\"", "");
        if (!code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        UserInfo userInfo = null;
        //判断传过来的是否有openid，如果有代表是扫码过后绑定手机号
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            //根据openid查询用户信息
            userInfo = this.selectWxUserInfoByOpenId(loginVo.getOpenid());
            if (!ObjectUtils.isEmpty(userInfo)) {
                //如果用户信息不为空，则更新用户信息，绑定手机号
                userInfo.setPhone(phone);
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        //纯手机号登录
//        if (userInfo == null) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, phone);
        userInfo = baseMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(userInfo)) {
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
//        }
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }

        result.put("name", name);
        //TODO JWT token生成
        String token = JwtHelper.createToken(userInfo.getId(), name);
        result.put("token", token);
        return result;
    }

    @Override
    public UserInfo selectWxUserInfoByOpenId(String openid) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenid, openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        if (!ObjectUtils.isEmpty(userInfo)) {
            userInfo.setName(userAuthVo.getName());
            userInfo.setCertificatesType(userAuthVo.getCertificatesType());
            userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
            userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
            userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
            baseMapper.updateById(userInfo);
            return true;
        }
        return false;
    }

    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        String name = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        //对条件值做判断
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, UserInfo::getName, name)
                .or().eq(status != null, UserInfo::getStatus, status)
                .or().eq(authStatus != null, UserInfo::getAuthStatus, authStatus)
                .or().ge(createTimeBegin != null, UserInfo::getCreateTime, createTimeBegin)
                .or().le(createTimeEnd != null, UserInfo::getCreateTime, createTimeEnd);
        Page<UserInfo> page = baseMapper.selectPage(pageParam, queryWrapper);
        page.getRecords().stream().forEach(i -> {
            this.packageUserInfo(i);
        });
        return page;
    }

    @Override
    public boolean lock(Long userId, Long status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(Math.toIntExact(status));
            int result = baseMapper.updateById(userInfo);
            return result > 0 ? true : false;
        }
        return false;
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> paramMap = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(id);
        paramMap.put("userInfo", this.packageUserInfo(userInfo));
        //根据id查询用户就诊信息
        List<Patient> list = patientService.finAllByUserId(id);
        paramMap.put("patientList", list);
        return paramMap;
    }

    @Override
    public boolean approval(Long userId, Integer authStatus) {
        if (authStatus.intValue() == 2 || authStatus.intValue() == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            int result = baseMapper.updateById(userInfo);
            return result > 0 ? true : false;
        }
        return false;
    }

    public UserInfo packageUserInfo(UserInfo userInfo) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statusString", userInfo.getStatus() == 0 ? "锁定" : "正常");
        paramMap.put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        userInfo.setParam(paramMap);
        return userInfo;
    }

}
